﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfCustomControlLibrary5
{
    public class MyCanvas : Panel
    {
        public static readonly DependencyProperty TopProperty = DependencyProperty.Register("Top", typeof(double), typeof(MyCanvas));
        public static readonly DependencyProperty LeftProperty = DependencyProperty.Register("Left", typeof(double), typeof(MyCanvas));

        public static double GetTop(DependencyObject obj)
        {
            return (double)obj.GetValue(TopProperty);
        }

        public static void SetTop(DependencyObject obj, double value)
        {
           obj.SetValue(TopProperty, value); 
        }

        public static double GetLeft(DependencyObject obj)
        {
            return (double)(obj.GetValue(LeftProperty));
        }

        public static void SetLeft(DependencyObject obj, double value)
        {
            obj.SetValue(LeftProperty, value);
        }


        protected override Size MeasureOverride(Size availableSize)
        {
            foreach (UIElement item in InternalChildren)
            {
                Size size = new Size(Double.PositiveInfinity, Double.PositiveInfinity);

                //子元素自己测量
                item.Measure(size);

                Size s = item.DesiredSize;//存储了测量之后的实际空间大小
            }

            return new Size();
        }

        /// <summary>
        /// 布局子元素
        /// </summary>
        /// <param name="finalSize"></param>
        /// <returns></returns>
        protected override Size ArrangeOverride(Size finalSize)
        {
            foreach (UIElement item in InternalChildren)
            {
                //进行子元素布局
                double x = 0, y = 0; 

                x = MyCanvas.GetLeft(item);
                y = MyCanvas.GetTop(item);

                item.Arrange(new Rect(new Point(x,y), item.DesiredSize));
            }

            return finalSize;
        }
    }
}
